﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using HXDNB.Model;
using System.Data.Objects.SqlClient;

namespace HXDNB.DAL
{
    public class ArticleBLL : IDisposable
    {
        readonly Entities _e = new Entities();

        /// <summary>
        /// 根据ID查询单个文章
        /// </summary>
        public Article Get(int id)
        {
            var info = (from i in _e.Articles where i.ID == id select i).SingleOrDefault();
            return info;
        }

        /// <summary>
        /// 根据栏目ID查询文章数目
        /// </summary>
        public int GetCount(int id)
        {
            int count = _e.Articles.Count(i => i.MeunId == id);
            return count;
        }

        /// <summary>
        /// 查询文章列表
        /// </summary>
        public IQueryable<ArticleListModel> GetList(string title, int? MeunID)
        {
            var list = from i in _e.Articles select i;
            if (string.IsNullOrWhiteSpace(title) == false)
            {
                list = list.Where(i => i.Title.Contains(title));
            }
            if (MeunID != null && MeunID > 0)
            {
                list = list.Where(i => i.MeunId == (int)MeunID);
            }
            List<Meun> meunlist = new List<Meun>();
            new MeunBLL().GetALLSort(0, ref meunlist);
            string meuns = string.Empty;
            foreach (Meun item in meunlist)
            {
                meuns += "," + item.ID;
            }
            var newlist = from i in list
                          join j in _e.Meuns on i.MeunId equals j.ID
                          where meuns.Contains(SqlFunctions.StringConvert((decimal)i.MeunId).Trim())
                          orderby i.UpdateTime descending
                          select new ArticleListModel { ID = i.ID, Title = i.Title, UpdateTime = i.UpdateTime, CreateTime = i.CreateTime, Thumbnail = i.Thumbnail, MeunName = j.Name ?? "栏目不存在", IsRelease = i.IsRelease };
            return newlist.AsQueryable();
        }

        /// <summary>
        /// 获取未发布文章
        /// </summary>
        public IList<Article> GetUnReleaseArticles()
        {
            return _e.Articles.Where(a => a.IsRelease == "N").OrderByDescending(a => a.Sort).ThenByDescending(a => a.CreateTime).ToList();
        }

        /// <summary>
        /// 获取所有文章
        /// </summary>
        public IList<Article> GetAllArticles()
        {
            return _e.Articles.OrderByDescending(a => a.Sort).ThenByDescending(a => a.CreateTime).ToList();
        }

        /// <summary>
        /// 根据栏目获取文章
        /// </summary>
        public IEnumerable<Article> GetArticlesByMenuId(int menuId)
        {
            return _e.Articles.Where(a => a.MeunId == menuId).OrderByDescending(a => a.Sort).ThenByDescending(a => a.CreateTime).ToList();
        }

        /// <summary>
        /// 根据栏目获取指定数目的文章
        /// </summary>
        public IEnumerable<Article> GetArticlesByMenuId(string[] menus, int count)
        {
            return _e.Articles.ToList().Where(a => menus.Contains((a.MeunId ?? 0).ToString()))
                                     .OrderByDescending(a => a.Sort).ThenByDescending(a => a.CreateTime)
                                     .Take(count);
        }

        /// <summary>
        /// 添加文章
        /// </summary>
        public int Add(Article model)
        {
            string err = null;
            model.UpdateTime = DateTime.Now;
            model.CreateTime = DateTime.Now;
            model.IsRelease = "N";
            try
            {
                _e.Articles.AddObject(model);
                _e.SaveChanges();
            }
            catch (Exception e)
            {
                err = e.Message;
                model.ID = 0;
            }
            finally
            {
                string msg = string.Format("添加文章[ID:{0},标题:{1}]", model.ID, model.Title);
                new LogBLL().Add(LogType.文章日志, msg, model.ID > 0, err);
            }
            return model.ID;//添加成功返回自增ID
        }

        /// <summary>
        /// 修改文章
        /// </summary>
        public bool Edit(Article model)
        {
            string err = null;
            bool result = false;
            model.UpdateTime = DateTime.Now;
            model.IsRelease = "N";
            try
            {
                var info = Get(model.ID);
                if (info != null)
                {
                    model.CreateTime = info.CreateTime;
                    _e.Articles.Detach(info);
                    _e.Articles.Attach(model);
                    _e.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "文章不存在";
                }
            }
            catch (Exception e)
            {
                err = e.Message;
                result = false;
            }
            finally
            {
                string msg = string.Format("编辑文章[ID:{0},标题:{1}]", model.ID, model.Title);
                new LogBLL().Add(LogType.文章日志, msg, result, err);
            }
            return result;
        }

        /// <summary>
        /// 修改文章发布状态为已发布
        /// </summary>
        public bool Publish(int id)
        {
            try
            {
                var info = Get(id);
                info.IsRelease = "Y";
                //info.UpdateTime = DateTime.Now;
                return _e.SaveChanges() > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 根据ID删除文章
        /// </summary>
        public bool Delete(int id)
        {
            bool result = false;
            string err = null;
            var info = Get(id);
            try
            {
                if (info != null)
                {
                    _e.Articles.DeleteObject(info);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "文章不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                err = e.Message;
            }
            finally
            {
                string msg = string.Format("删除文章[ID:{0},标题:{1}]", id, (info ?? new Article()).Title);
                new LogBLL().Add(LogType.文章日志, msg, result, err);
            }
            return result;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}
